package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.service.mapper.BUserMapper;
import com.youhome.service.mapper.BUserRoleMapper;
import com.youhome.service.model.*;
import com.youhome.service.service.BCompanyService;
import com.youhome.service.service.BUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Created by chen365 on 2017/10/19.
 */

@Service
public class BUserServiceImpl implements BUserService {

    @Autowired
    BCompanyService bCompanyService;
    @Autowired
    private BUserMapper bUserMapper;
    @Autowired
    private BUserRoleMapper bUserRoleMapper;

    @Override
    public BUser getCurrentUser(String openid) {
        BUser user = bUserMapper.selectByOpenId(openid);
        return user;
    }

    @Override
    public BUser create(BUser user) {
        if (bUserMapper.insert(user) == 1) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public int create(BUserRole userRole) {
        return bUserRoleMapper.insert(userRole);
    }

    @Override
    public BUser getCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Principal principal = (Principal) authentication.getPrincipal();
            return principal.getUser();
        } catch (Exception e) {
            //e.printStackTrace();
            return null;
        }
    }

    @Override
    public BUser selectByPhone(String phone) {
        return bUserMapper.selectByPhone(phone);
    }

    @Override
    public Boolean isExistByPhone(String phone) {
        if (bUserMapper.selectByPhone(phone) != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public PageInfo<Contacts> selectContactsByCompanyId(Integer page, Integer pageSize, Long companyId) {
        if (page == null || page < 1)
            page = 1;

        if (pageSize == null || pageSize < 1)
            pageSize = 10;

        PageHelper.startPage(page, pageSize);
        List<Contacts> list = bUserMapper.selectContactsByCompanyId(companyId);
        return new PageInfo<>(list);
    }

    @Override
    public Long getCompanyId() {
        BUser currentUser = getCurrentUser();
        if (currentUser != null) {
            BCompany company = bCompanyService.selectByUserId(currentUser.getUserId());
            if (company != null) {
                return company.getCompanyId();
            }
        }
        return null;
    }

    @Override
    public int updateReportCount(Integer count, Long id) throws Exception {
        BUser user = new BUser();
        user.setUserId(id);
        user.setReportCount(count);
        return bUserMapper.updateReportCount(user);
    }

    @Override
    public int findRepotCountById(Long id) throws Exception {
        return bUserMapper.selectRepotCountById(id);
    }

    @Override
    public int updateByPrimaryKeySelective(BUser entity) {
        return bUserMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        System.err.println("===================logout==============================");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        new SecurityContextLogoutHandler().logout(request, response, auth);
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            Arrays.stream(cookies).forEach(cookie -> {
                if (cookie.getName().equalsIgnoreCase("remember-me")) {
                    cookie.setMaxAge(0);
                    cookie.setValue(null);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            });
        }
    }

    @Override
    public int selectReportCount() throws CustomException {
        BUser currentUser = getCurrentUser();
        return bUserMapper.selectRepotCountById(currentUser.getUserId());
    }
}
